/*
 * @lc app=leetcode.cn id=1277 lang=cpp
 *
 * [1277] 统计全为 1 的正方形子矩阵
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

// @lc code=start
class Solution {
public:
    int countSquares(vector<vector<int>>& matrix) {
        int result = 0;
        int m = matrix.size();          // 矩阵的行数
        if (m == 0) return result;
        int n = matrix[0].size();       // 矩阵的列数
        if (n == 0) return result;

        vector<vector<int>> f(m, vector<int>(n));       // 动态规划数组
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0) {
                    f[i][j] = matrix[i][j];
                } else if (matrix[i][j] == 0) {
                    f[i][j] = 0;
                } else {
                    f[i][j] = min(min(f[i - 1][j], f[i][j - 1]), f[i - 1][j - 1]) + 1;
                }
                result += f[i][j];
            }
        }
        
        return result;
    }
};
// @lc code=end

